#pragma once
#include "log.hpp"
#include "protocol.hpp"

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <wait.h>
#include <signal.h>
#include <functional>

#define NUM 1024

namespace Server
{

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };

    static const uint16_t gport = 8080;
    static const int gbacklog = 5;
    // const Request& 输入型参数
    // Request& 输出型参数
    typedef std::function<bool(const Request &req, Response &resp)> func_t;

    void handlerEntery(int sock, func_t func)
    {
        std::string inbuffer;
        while (true)
        {
            // "content_len"\r\n "x op y" \r\n
            // 1. 保证读取到的是一个完整的请求
            std::string req_text, req_str;
            if (!recvPackage(sock, inbuffer, &req_text))
                return;
            std::cout << "带报头的请求: \n"
                      << req_text << std::endl;
            // 1.1 去掉报头
            if (!deLength(req_text, &req_str))
                return;
            std::cout << "去掉报头的正文: \n"
                      << req_str << std::endl;
            // 2. 对处理过的请求进行反序列化
            // 2.1 得到一个结构化的对象
            Request req;
            if (!req.delserialize(req_str))
                return;
            // 3. 进行业务处理
            // 3.1 得到一个结构化的响应
            Response resp;
            func(req, resp);
            // 4. 对响应进行序列化
            // 4.1 得到一个字符串
            std::string resp_str;
            resp.serialize(&resp_str);
            std::cout << "计算完成，序列化响应: " << resp_str << std::endl;
            // 5. 添加报头
            std::string send_string = enLength(resp_str);
            std::cout << "构建成完整的响应: \n"
                      << send_string << std::endl;
            // 5.  发送响应
            send(sock, send_string.c_str(), send_string.size(), 0);
        }
    }

    class calServer
    {
    public:
        calServer(const uint16_t &port = gport)
            : _port(port), _listensock(-1)
        {
        }
        void initServer()
        {
            // 1.创建socket套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "create socket error!");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "create socket success!");
            // 2.bind自己的网络信息
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error!");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success!");
            // 3.设置socket listen监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error!");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success!");
        }
        void run(func_t func)
        {
            signal(SIGCHLD, SIG_IGN);
            for (;;)
            {
                // 4.获取链接
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error,next!");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success!");

                std::cout << "sock: " << sock << std::endl;
                pid_t id = fork();
                if (id == 0)
                {
                    close(_listensock);
                    // if(fork()>0) exit(0); 
                    handlerEntery(sock, func);
                    close(sock);
                    exit(0);
                }
                close(sock);
                // pid_t ret = waitpid(id, nullptr, 0);
                // if (ret > 0)
                // {
                //     logMessage(NORMAL, "wait child success!");
                // }
            }
        }

        ~calServer()
        {
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}
